package com.shiyi.controller;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

import static org.jacoco.agent.rt.internal_43f5073.core.runtime.AgentOptions.OutputMode.file;

/**
 * @ClassName HtmlToPdfUtils
 */
public class HtmlToPdfUtils {
    public static void html2Pdf(InputStream inputStream, String waterMark, OutputStream outputStream) throws
            IOException {
        PdfWriter pdfWriter = new PdfWriter(outputStream);
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
//        pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new WaterMarkEventHandler(waterMark));
//        pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new PageEventHandler());

        ConverterProperties properties = new ConverterProperties();
        //添加中文字体支持
        FontProvider fontProvider = new FontProvider();
        PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");
        properties.setFontProvider(fontProvider);

        HtmlConverter.convertToPdf(inputStream, pdfDocument, properties);

        pdfWriter.close();
        pdfDocument.close();
    }

    public static void main(String[] args) {
        //水印
        String waterMarkText = "bihe";
        File inputfile = new File("C:\\Users\\bihe\\Desktop\\htmlcode.html");

        File outputFile = new File("output.pdf");
        try {
            FileInputStream fileInputStream = new FileInputStream(inputfile);
            OutputStream os = new FileOutputStream(outputFile);
            HtmlToPdfUtils.html2Pdf(fileInputStream, waterMarkText, os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}